package com.tzinfo.tzb;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ClassList;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.util.FileConfig;
import com.tzinfo.tzb.util.HttpTools;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.view.util.ResFinder;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

public class HuiTieActivity extends TzbBaseActivity {
    private int fid = -1, tid = -1,ouid=-1;
    private String pid = null;
    private String tag = null;
    DefaultResult result = null;
    private Object imagePath = null;
    // UI组件
    private ImageView  img_tiezi_tupian,
            img_delete;
    private TextView text_title;
    private TextView text_tiezi_context;
    private AlertDialog dlg;
    private ClassList.ClassData.ClassSubMenu classSubMenu = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hui_tie);

        init();
    }
    private void init() {
        // 加载滚动进入条
        mProgressBar = (ProgressBar) ResFinder.findViewById(this,
                "R.id.progressbar_loding");


        img_tiezi_tupian = (ImageView) ResFinder.findViewById(this,
                "R.id.img_tiezi_tupian");
        img_delete = (ImageView) ResFinder
                .findViewById(this, "R.id.img_delete");

        text_tiezi_context = (TextView) ResFinder.findViewById(this,
                "R.id.text_tiezi_context");
        fid=getIntent().getIntExtra("fid",-1);
        tid=getIntent().getIntExtra("tid",-1);
        ouid=getIntent().getIntExtra("ouid", -1);
        tag = getIntent().getStringExtra("tag");
    }
    public void fabuTiezi(View v) throws UnsupportedEncodingException {
        // showProgressBar();
        dialog.show();
        String url = "";
        if (fid == -1 || tid == -1) {
            Toast.makeText(this, "发布失败", Toast.LENGTH_SHORT).show();
            finish();
        } else {
                String string = tag+ text_tiezi_context.getText().toString();
            url = getResources().getString(R.string.tzb_url_ForumpostPub) + "?fid=" + fid + "&tid=" + tid  + "&message="
                    + URLEncoder.encode(string,"UTF-8") + "&sessionid="
                    + TztData.userInfo.getData().getSessionID()+"&ouid="+ouid;
        }

        OutLog.LogE("yxw", url);
        OutLog.LogE("ouid=", ""+ouid);
        OutLog.LogE("tag=", ""+tag);
        OutLog.LogE("sessionid=", ""+TztData.userInfo.getData().getSessionID());
        GalHttpRequest galHttpRequest = new GalHttpRequest(this);
        galHttpRequest.setCacheEnable(false);
        galHttpRequest.setURL(url);
        galHttpRequest.startAsynRequestString(new GalHttpRequest.GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                OutLog.LogE("yxw", "json:" + arg0);
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                }.getType();
                result = gson.fromJson(arg0, type);
                if (result.isSuccess()) {
                    pid = result.getMsg();
                    if (fid == -1 || tid == -1) {
                        Toast.makeText(HuiTieActivity.this, "恭喜你，发帖成功！",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(HuiTieActivity.this, "恭喜你，回帖成功！",
                                Toast.LENGTH_SHORT).show();
                    }
                    if (imagePath instanceof String) {
                        Toast.makeText(HuiTieActivity.this, "开始上传图片！",
                                Toast.LENGTH_SHORT).show();
                        new Thread(upLoadImageRun).start();
                    } else {
                        back();
                        dialog.dismiss();
                    }

                } else {
                    Toast.makeText(HuiTieActivity.this, "抱歉，发帖失败，请重试！", Toast.LENGTH_SHORT)
                            .show();
                }
                // removeProgressBar();

            }
        });
    }

    private void back() {
        Intent intent = new Intent();
        setResult(2, intent);
        HuiTieActivity.this.finish();
    }

    Runnable upLoadImageRun = new Runnable() {

        @Override
        public void run() {
            Message message = handler.obtainMessage();
            String url = ResFinder.getResString(HuiTieActivity.this,
                    "R.string.tzb_url_attachment_Add")
                    + "?sessionid="
                    + TztData.userInfo.getData().getSessionID() + "&pid=" + pid;
            OutLog.LogE("yxw", "add:" + url);
            String path = (String) imagePath;
            if (path != null) {
                String jsonString = HttpTools.uploadImage(url, path);
                Log.e("yxw", "jsonImage:" + jsonString);
                DefaultResult result = null;
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                }.getType();
                result = gson.fromJson(jsonString, type);
                if (result.isSuccess()) {
                    message.arg1 = 1;
                } else {
                    message.arg1 = -1;
                }
            }
            handler.sendMessage(message);
        }
    };
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 1:
                    dialog.dismiss();
                    Toast.makeText(HuiTieActivity.this, "图片上传成功！",
                            Toast.LENGTH_SHORT).show();
                    back();
                    break;
                case -1:
                    dialog.dismiss();
                    Toast.makeText(HuiTieActivity.this, "图片上传失败！",
                            Toast.LENGTH_SHORT).show();
                    back();
                    break;
            }
        }
    };

    private void deleteImage(Object object) {
        if (object instanceof String) {
            dialog.show();
            img_tiezi_tupian.setImageResource(R.drawable.tzb_image_add);
            img_delete.setVisibility(View.GONE);
            imagePath = null;
            Toast.makeText(HuiTieActivity.this, "已删除图片！",
                    Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        } else {// 网络的删除需要通过HTTP请求
        }

    }

    // 删除图片
    public void onDeleteImage(View v) {
        new AlertDialog.Builder(HuiTieActivity.this)
                .setTitle("友情提醒")
                .setMessage("您确定要删除这张照片吗？")
                .setPositiveButton("确	定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                deleteImage(imagePath);
                            }
                        })
                .setNegativeButton("取	消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                            }
                        }).show();
    }

    // 显示选择相册or照片
    public void showAddImageDialog(View v) {
        if (!(imagePath instanceof DiaryList.DiaryData.DiaryPhoto)
                && img_delete.getVisibility() != View.VISIBLE) {
            final CharSequence[] items = {"相册", "拍照", "取消"};

            dlg = new AlertDialog.Builder(this).setTitle("选择照片")
                    .setItems(items, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            // 这里item是根据选择的方式，
                            // 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
                            if (which == 0) {
                                Intent getImage = new Intent(
                                        Intent.ACTION_GET_CONTENT);
                                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                                getImage.setType("image/jpeg");
                                startActivityForResult(getImage, 2);
                            } else if (which == 1) {
                                Intent getImageByCamera = new Intent(
                                        "android.media.action.IMAGE_CAPTURE");
                                File tempFile = new File(FileConfig.IMAGE_PATH);
                                if (!tempFile.isDirectory()) {
                                    tempFile.mkdirs();
                                }
                                FileConfig.IMAGE_NAME = FileConfig
                                        .getRandomJpgName();
                                Uri imageUri = Uri.fromFile(new File(
                                        FileConfig.IMAGE_PATH,
                                        FileConfig.IMAGE_NAME));
                                // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                                getImageByCamera.putExtra(
                                        MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(getImageByCamera, 3);
                            } else {
                                dlg.dismiss();
                            }
                        }
                    }).create();
            dlg.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        BitmapFactory.Options option = null;
        switch (requestCode) {
            case 2:
                if (data != null) {
                    img_delete.setVisibility(View.VISIBLE);
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
                    option = new BitmapFactory.Options();
                    option.inSampleSize = 5;
                    imagePath = picturePath;
                    img_tiezi_tupian.setImageBitmap(BitmapFactory.decodeFile(
                            picturePath, option));
                }
                break;
            case 3:
                img_delete.setVisibility(View.VISIBLE);
                // 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
                option = new BitmapFactory.Options();
                String path = FileConfig.IMAGE_PATH + "/" + FileConfig.IMAGE_NAME;
                option.inSampleSize = 5;
                imagePath = path;
                img_tiezi_tupian.setImageBitmap(BitmapFactory.decodeFile(path,
                        option));
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
